package com.qf58.search.utils;

import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import com.qf58.search.convert.MapDeserialize;

import java.lang.reflect.Type;
import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: zhubo
 * Date: 2017-08-31
 * Time: 9:59
 */
public class GsonUtils {
    //不完善的自定义反序列化
    public static Gson getMapConvertGson(){
        Gson gson = new GsonBuilder().registerTypeAdapter(new TypeToken<HashMap<String, Object>>(){}.getType(),new MapDeserialize()).create();
        return  gson;
    }

    public static Gson getDoubleConvertGson(){
        Gson gson = new GsonBuilder().registerTypeAdapter(Double.class, new JsonSerializer<Double>() {
            @Override
            public JsonElement serialize(Double aDouble, Type type, JsonSerializationContext jsonSerializationContext) {
                if(aDouble == aDouble.longValue()){
                    return new JsonPrimitive(aDouble.longValue());
                }else{
                    return new JsonPrimitive(aDouble);
                }
            }
        }).create();
        return gson;
    }
}
